package com.base.control;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

/**
 * Created by yjh on 15-3-11.
 */
//TODO 横竖屏切换
public abstract class MDialog extends Dialog {
    private MActivitySupport mActivitySupport;

    public MDialog(MActivitySupport context) {
        super(context);
        this.mActivitySupport = context;
    }

    public MDialog(MActivitySupport context, int theme) {
        super(context, theme);
        this.mActivitySupport = context;
    }

    public MDialog(MActivitySupport context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        this.mActivitySupport = context;
    }

    public MActivitySupport getMActivity() {
        return this.mActivitySupport;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        create(savedInstanceState);
    }

    public abstract void create(Bundle savedInstanceState);

    public <T> T mfindViewById(int id) {
        return (T)super.findViewById(id);
    }

    public View.OnClickListener getDefaultListener() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MDialog.this.dismiss();
            }
        };
    }

    public void addOnClickListener(View v, View.OnClickListener listener) {
        if(listener != null) {
            v.setOnClickListener(listener);
        } else {
            v.setOnClickListener(getDefaultListener());
        }
    }

    public DisplayMetrics getMetrics() {
        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);

        DisplayMetrics metrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metrics);

        return metrics;
    }

    public void setDialogWithFullScreen(int gravityFlag) {
        Window dialogWindow = this.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(gravityFlag);

        lp.width = getMetrics().widthPixels;
        dialogWindow.setAttributes(lp);
    }
}
